package project.innovation.mooddiagnosis.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import project.innovation.mooddiagnosis.vo.ChatRequestParameter;
import project.innovation.mooddiagnosis.vo.ChatResponseParameter;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

@Component
@Slf4j
public class MindChat {
    private final Charset charset = StandardCharsets.UTF_8;
    @Value("${ShellPath_mind_chat}")
    private String shellPathMindChat;
    @Value("${ShellPath_get_mindchat_response}")
    private String shellPathGetMindchatResponse;
    @Value("${ShellPath_remove_mindchat_response}")
    private String shellPathRemoveMindchatResponse;
    @Value("${MindChatResponsePath}")
    private String mindchatResponsePath;

    Executor executor = new Executor();

    @Autowired
    public void setexecutor(Executor executor) {
        this.executor = executor;
    }

    /**
     * 仅提交message
     */
    public void sendMessage(String userId, ChatRequestParameter parameter) throws IOException, InterruptedException {
        log.info("sendMessage userId = {}, parameter = {}", userId, parameter);
        String valueAsString = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try{
            valueAsString = objectMapper.writeValueAsString(parameter);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        log.info("sendMessage valueAsString = {}", valueAsString);
        try {
            log.info("sendMessage shellPath = {}", shellPathMindChat);
            executor.executeExpect(shellPathMindChat, userId, valueAsString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 不断查询服务器上是否产生返回文件
     */
    public String getAnswer(String userId) throws Exception {
        log.info("getAnswer userId = {}", userId);
        String result = null;
        for(int i=0;i<30;i++){
            executor.executeExpect(shellPathGetMindchatResponse, userId);
            result = checkresponse(userId);
            if (!Objects.equals(result, null)){
                return result;
            } else {
                try{
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        result = "network error. try again";
        return result;
    }

    String checkresponse(String userId) throws Exception {
        String ret = null;
        String fileName = userId+".json";
        Path filePath = Paths.get(mindchatResponsePath,fileName);
        log.info("checkresponse filePath = {}", filePath);
        if(Files.exists(filePath)){
            log.info("file exists {}", fileName);
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                ChatResponseParameter response =  objectMapper.readValue(new File(filePath.toString()), ChatResponseParameter.class);
                ret = response.getResponse();
                log.info("response ret = {}", ret);
                executor.executeExpect(shellPathRemoveMindchatResponse, userId);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }
}
